package com.tian.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tian.common.CommonResult;
import com.tian.dto.CarAreaModelDto;
import com.tian.dto.CarAreaModelListRespDto;
import com.tian.entity.CarAreaModel;
import com.tian.util.CarAreaUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * {@code @description:} TODO
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-03-26 11:27
 * {@code @version:} 1.0
 */
@Slf4j
@RestController
@RequestMapping("/car/area")
public class CarAreaController {
    /**
     * 车牌号归属地JSON
     */
    @GetMapping("list")
    public CommonResult<CarAreaModelListRespDto> list() {
        List<CarAreaModel> carAreaJSON = this.getCarAreaJSON();

        CarAreaModelListRespDto carAreaModelListRespDto = new CarAreaModelListRespDto();
        List<CarAreaModelDto> carAreaModelDtoList = new ArrayList<>();
        for (CarAreaModel carAreaModel : carAreaJSON) {
            CarAreaModelDto carAreaModelDto = new CarAreaModelDto();
            BeanUtils.copyProperties(carAreaModel, carAreaModelDto);
            carAreaModelDtoList.add(carAreaModelDto);
        }
        carAreaModelListRespDto.setCarAreaModelDtoList(carAreaModelDtoList);
        return CommonResult.success(carAreaModelListRespDto);
    }

    public List<CarAreaModel> getCarAreaJSON() {
        InputStream inputStream = getClass().getResourceAsStream("/carArea.json");
        if (inputStream == null) {
            log.error("读取车牌归属地json文件失败！！");
            return null;
        } else {
            JSONObject json = null;
            try {
                json = JSON.parseObject(inputStream, JSONObject.class);
            } catch (IOException e) {
                log.error("读取车牌归属文件格式转换json失败");
                return null;
            }
            JSONArray array = json.getJSONArray("codeInfo");
            return array.toJavaList(CarAreaModel.class);
        }

    }

}
